/**
 * Project Name:kany-project-blog-web
 * File Name:SecurityContextAuthorizer.java
 * Package Name:me.kany.project.blog.resource.filter
 * Date:2016年9月21日下午5:08:55
 * Copyright (c) 2016, Jason.Wang All Rights Reserved.
 */
package me.kany.project.blog.resource.filter;

import java.security.Principal;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import javax.inject.Provider;
import javax.security.auth.Subject;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.core.UriInfo;

/**
 * ClassName:SecurityContextAuthorizer<br/>
 * Function: 安全上下文认证的创建<br/>
 * Date:2016年9月21日下午5:08:55<br/>
 * 
 * @author Jason.Wang
 * @version 1.0
 * @since JDK1.7
 * @see
 */
public class SecurityContextAuthorizer implements SecurityContext {

	private Principal principal;
	private Provider<UriInfo> uriInfo;
	private Set<String> roles;

	public SecurityContextAuthorizer(final Provider<UriInfo> uriInfo, final Principal principal, final String[] roles) {
		this.principal = principal;
		if (principal == null) {
			this.principal = new Principal() {
				@Override
				public String getName() {
					return "anonymous";
				}
				@SuppressWarnings("unused")
				public boolean implies(Subject subject) {
					return true;
				}
			};
		}
		this.uriInfo = uriInfo;
		this.roles = new HashSet<>(Arrays.asList((roles != null) ? roles : new String[] {}));
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.ws.rs.core.SecurityContext#getUserPrincipal()
	 */
	@Override
	public Principal getUserPrincipal() {
		return this.principal;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.ws.rs.core.SecurityContext#isUserInRole(java.lang.String)
	 */
	@Override
	public boolean isUserInRole(String role) {
		return this.roles.contains(((role == null) ? "" : role));
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.ws.rs.core.SecurityContext#isSecure()
	 */
	@Override
	public boolean isSecure() {
		return "https".equals(uriInfo.get().getRequestUri().getScheme());
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.ws.rs.core.SecurityContext#getAuthenticationScheme()
	 */
	@Override
	public String getAuthenticationScheme() {
		return SecurityContext.DIGEST_AUTH;
	}

}
